<template>
  <div class="orders-container">
    <div class="header">
      <h2>订单管理</h2>
      <div class="header-actions">
        <el-button 
          v-if="userStore.isSuperAdmin" 
          type="primary"
          @click="createTestOrder"
        >创建测试订单(待付款)</el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="订单号">
        <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="待付款" value="PENDING" />
          <el-option label="已付款" value="PAID" />
          <el-option label="已发货" value="SHIPPED" />
          <el-option label="已完成" value="COMPLETED" />
          <el-option label="已取消" value="CANCELLED" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单列表 -->
    <el-table
      v-loading="loading"
      :data="orders"
      border
      style="width: 100%"
    >
      <el-table-column prop="orderId" label="订单ID" width="100" />
      <el-table-column prop="orderNo" label="订单编号" width="180" />
      <el-table-column prop="shippingName" label="收货人" width="120" />
      <el-table-column prop="totalAmount" label="订单金额" width="120">
        <template #default="{ row }">
          {{ formatPrice(row.totalAmount) }}
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="购买数量" width="100" />
      <el-table-column prop="status" label="订单状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="280">
        <template #default="{ row }">
          <el-button-group>
            <!-- 查看按钮对所有角色可见 -->
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            
            <!-- 超级管理员可以编辑所有订单，普通用户只能编辑自己的待付款订单 -->
            <el-button 
              v-if="(userStore.isSuperAdmin || (userStore.isUser && isUserOrder(row) && row.status === 'PENDING'))"
              type="primary" 
              link 
              :disabled="row.status !== 'PENDING'"
              @click="handleEdit(row)"
            >修改</el-button>
            
            <!-- 付款按钮 - 只对待付款状态的订单显示，超级管理员和订单所有者可见 -->
            <el-button 
              v-if="(userStore.isSuperAdmin || (userStore.isUser && isUserOrder(row))) && row.status === 'PENDING'"
              type="success" 
              link 
              @click="handlePay(row)"
            >付款</el-button>
            
            <!-- 发货按钮 - 只对已付款状态的订单显示，超级管理员和管理员可见 -->
            <el-button 
              v-if="(userStore.isSuperAdmin || userStore.isAdmin) && row.status === 'PAID'"
              type="warning" 
              link 
              @click="handleShipping(row)"
            >发货</el-button>
            
            <!-- 完成按钮 - 只对已发货状态的订单显示，超级管理员和管理员可见 -->
            <el-button 
              v-if="(userStore.isSuperAdmin || userStore.isAdmin) && row.status === 'SHIPPED'"
              type="success" 
              link 
              @click="handleComplete(row)"
            >完成</el-button>
            
            <!-- 取消按钮 - 只对待付款状态的订单显示，超级管理员和订单所有者可见 -->
            <el-button 
              v-if="(userStore.isSuperAdmin || (userStore.isUser && isUserOrder(row))) && row.status === 'PENDING'"
              type="danger" 
              link 
              @click="handleCancel(row)"
            >取消</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
      />
    </div>

    <!-- 订单表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="'修改订单数量'"
      width="400px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="订单编号">
          <span>{{ form.orderNo }}</span>
        </el-form-item>
        <el-form-item label="商品名称">
          <span>{{ form.productName }}</span>
        </el-form-item>
        <el-form-item label="单价">
          <span>{{ formatPrice(form.productPrice) }}</span>
        </el-form-item>
        <el-form-item label="购买数量" prop="quantity">
          <el-input-number 
            v-model="form.quantity" 
            :min="1"
            :max="999"
            @change="handleQuantityChange"
          />
        </el-form-item>
        <el-form-item label="总金额">
          <span>{{ formatPrice(form.totalAmount) }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrders, updateOrder, deleteOrder, updateOrderQuantity, payOrder, updateOrderShippingStatus, cancelOrder, updateOrderStatus, completeOrder, createTestOrder as createTestOrderApi } from '@/api/order'
import { formatDate, formatPrice } from '@/utils/format'
import { useUserStore } from '@/store/modules/user'

// 初始化 store
const userStore = useUserStore()

// 数据列表
const orders = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  status: ''
})

// 表单对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  orderId: '',
  orderNo: '',
  shippingName: '',
  totalAmount: 0,
  status: ''
})

// 表单验证规则
const rules = {
  quantity: [
    { required: true, message: '请输入购买数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
}

// 发货对话框（移除）
const currentOrder = ref(null)

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 只有当有值时才添加搜索条件
    if (searchForm.orderNo && searchForm.orderNo.trim()) {
      params.orderNo = searchForm.orderNo.trim()
    }
    
    if (searchForm.status) {
      params.status = searchForm.status
    }
    
    // 如果是普通用户，只查询自己的订单
    if (userStore.isUser) {
      // 添加所有可能的用户标识字段
      const userIdentifiers = {};
      
      if (userStore.userId) {
        userIdentifiers.userId = userStore.userId;
      }
      
      if (userStore.username) {
        userIdentifiers.username = userStore.username;
        userIdentifiers.createdBy = userStore.username;
      }
      
      // 将所有标识字段添加到查询参数中
      Object.assign(params, userIdentifiers);
      
      console.log('普通用户查询自己的订单，添加用户标识:', userIdentifiers);
    }
    
    console.log('发送请求参数:', params)
    const res = await getOrders(params)
    console.log('订单数据响应:', res)
    
    if (res.code === 200) {
      // 处理不同的响应格式
      let orderData = []
      if (Array.isArray(res.data)) {
        orderData = res.data
        total.value = res.data.length
      } else if (res.data && res.data.records) {
        orderData = res.data.records
        total.value = res.data.total
      } else if (res.data) {
        orderData = [res.data]
        total.value = 1
      } else {
        orderData = []
        total.value = 0
      }
      
      // 对订单列表进行排序，按ID从小到大排序
      orders.value = [...orderData].sort((a, b) => {
        const idA = parseInt(a.orderId) || 0
        const idB = parseInt(b.orderId) || 0
        return idA - idB
      })
    } else {
      orders.value = []
      total.value = 0
      ElMessage.error(res.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
    orders.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 判断是否是用户自己的订单
const isUserOrder = (order) => {
  console.log('检查订单所有权:', {
    order: order,
    orderUserId: order.userId,
    orderUsername: order.username,
    orderCreatedBy: order.createdBy,
    storeUserId: userStore.userId,
    storeUsername: userStore.username
  });
  
  // 检查多种可能的匹配方式
  if (userStore.userId && order.userId) {
    return order.userId === userStore.userId;
  }
  
  if (order.username && userStore.username) {
    return order.username === userStore.username;
  }
  
  if (order.createdBy && userStore.username) {
    return order.createdBy === userStore.username;
  }
  
  // 如果订单有用户信息但当前用户没有对应信息，默认返回 false
  if ((order.userId || order.username || order.createdBy) && 
      (!userStore.userId && !userStore.username)) {
    return false;
  }
  
  // 如果是超级管理员，可以操作所有订单
  if (userStore.isSuperAdmin) {
    return true;
  }
  
  // 默认情况
  console.warn('无法确定订单所有权，默认允许操作');
  return true;
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  console.log('执行搜索，条件:', {
    orderNo: searchForm.orderNo,
    status: searchForm.status
  })
  fetchOrders()
}

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = ''
  searchForm.status = ''
  currentPage.value = 1
  console.log('重置搜索条件')
  fetchOrders()
}

// 编辑订单
const handleEdit = (row) => {
  // 检查权限
  if (!userStore.isSuperAdmin && !(userStore.isUser && isUserOrder(row) && row.status === 'PENDING')) {
    ElMessage.warning('您没有权限修改此订单')
    return
  }
  
  if (row.status !== 'PENDING') {
    ElMessage.warning('只有待付款状态的订单可以修改')
    return
  }
  
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 查看订单
const handleView = (row) => {
  // TODO: 实现查看订单详情
  console.log('查看订单:', row)
}

// 处理数量变化
const handleQuantityChange = (value) => {
  if (value <= 0) {
    ElMessage.warning('购买数量必须大于0')
    return
  }
  form.totalAmount = form.productPrice * value
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要将订单 ${form.orderNo} 的购买数量修改为 ${form.quantity} 吗？`,
      '确认修改',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    try {
      await updateOrderQuantity(form.orderId, form.quantity)
      ElMessage.success('修改成功')
      dialogVisible.value = false
      fetchOrders()
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message || '未知错误'
      if (errorMsg.includes('库存不足')) {
        ElMessage.error('商品库存不足，请重新选择数量')
      } else if (errorMsg.includes('订单不存在')) {
        ElMessage.error('订单不存在或已被删除')
        dialogVisible.value = false
        fetchOrders()
      } else {
        ElMessage.error('修改失败：' + errorMsg)
      }
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('提交失败:', error)
    ElMessage.error('表单验证失败，请检查输入')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchOrders()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'PAID': 'success',
    'SHIPPED': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '待付款',
    'PAID': '已付款',
    'SHIPPED': '已发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 处理付款
const handlePay = async (row) => {
  // 检查权限
  if (!userStore.isSuperAdmin && !(userStore.isUser && isUserOrder(row))) {
    ElMessage.warning('您没有权限对此订单付款')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要支付订单 ${row.orderNo} 吗？订单金额：${formatPrice(row.totalAmount)}`,
      '确认支付',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    try {
      await payOrder(row.orderId)
      ElMessage.success('支付成功')
      fetchOrders() // 刷新订单列表
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message || '未知错误'
      if (errorMsg.includes('订单不存在')) {
        ElMessage.error('订单不存在或已被删除')
      } else if (errorMsg.includes('状态')) {
        ElMessage.error('订单状态已改变，无法支付')
      } else {
        ElMessage.error('支付失败：' + errorMsg)
      }
      fetchOrders() // 刷新订单列表以获取最新状态
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('支付操作失败:', error)
  }
}

// 处理发货
const handleShipping = (row) => {
  // 检查权限
  if (!userStore.isSuperAdmin && !userStore.isAdmin) {
    ElMessage.warning('您没有权限进行发货操作')
    return
  }
  
  if (row.status !== 'PAID') {
    ElMessage.warning('只有已付款的订单可以进行发货操作')
    return
  }
  
  // 直接显示确认对话框
  ElMessageBox.confirm(
    `确定要将订单 ${row.orderNo} 标记为已发货吗？`,
    '确认发货',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  )
  .then(async () => {
    try {
      await updateOrderShippingStatus(row.orderId, 'SHIPPED')
      ElMessage.success('订单已发货')
      fetchOrders() // 刷新订单列表
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message || '未知错误'
      if (errorMsg.includes('订单不存在')) {
        ElMessage.error('订单不存在或已被删除')
      } else if (errorMsg.includes('状态')) {
        ElMessage.error('订单状态已改变，无法进行此操作')
      } else {
        ElMessage.error('操作失败：' + errorMsg)
      }
      fetchOrders() // 刷新订单列表以获取最新状态
    }
  })
  .catch(() => {
    // 用户取消操作
  })
}

// 处理完成订单
const handleComplete = (row) => {
  // 检查权限
  if (!userStore.isSuperAdmin && !userStore.isAdmin) {
    ElMessage.warning('您没有权限进行完成操作')
    return
  }
  
  if (row.status !== 'SHIPPED') {
    ElMessage.warning('只有已发货的订单可以标记为已完成')
    return
  }
  
  // 显示确认对话框
  ElMessageBox.confirm(
    `确定要将订单 ${row.orderNo} 标记为已完成吗？`,
    '确认完成',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  )
  .then(async () => {
    try {
      // 使用 completeOrder API
      await completeOrder(row.orderId)
      ElMessage.success('订单已完成')
      fetchOrders() // 刷新订单列表
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message || '未知错误'
      if (errorMsg.includes('订单不存在')) {
        ElMessage.error('订单不存在或已被删除')
      } else if (errorMsg.includes('状态')) {
        ElMessage.error('订单状态已改变，无法进行此操作')
      } else {
        ElMessage.error('操作失败：' + errorMsg)
      }
      fetchOrders() // 刷新订单列表以获取最新状态
    }
  })
  .catch(() => {
    // 用户取消操作
  })
}

// 处理取消
const handleCancel = (row) => {
  // 检查权限
  if (!userStore.isSuperAdmin && !(userStore.isUser && isUserOrder(row))) {
    ElMessage.warning('您没有权限取消此订单')
    return
  }
  
  if (row.status !== 'PENDING') {
    ElMessage.warning('只有待付款状态的订单可以取消')
    return
  }
  
  // 显示确认对话框
  ElMessageBox.confirm(
    `确定要取消订单 ${row.orderNo} 吗？`,
    '确认取消',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(async () => {
    try {
      await cancelOrder(row.orderId)
      ElMessage.success('订单已取消')
      fetchOrders()
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message || '未知错误'
      if (errorMsg.includes('订单不存在')) {
        ElMessage.error('订单不存在或已被删除')
      } else if (errorMsg.includes('状态')) {
        ElMessage.error('订单状态已改变，无法取消')
      } else {
        ElMessage.error('取消失败：' + errorMsg)
      }
    }
  })
  .catch(() => {
    // 取消操作
  })
}

// 创建测试订单
const createTestOrder = async () => {
  // 检查权限
  if (!userStore.isSuperAdmin) {
    ElMessage.warning('您没有权限创建测试订单')
    return
  }
  
  try {
    ElMessage.info('正在创建测试订单...')
    const res = await createTestOrderApi()
    if (res.code === 200) {
      ElMessage.success('测试订单创建成功')
      fetchOrders() // 刷新订单列表
    } else {
      ElMessage.error(res.message || '创建测试订单失败')
    }
  } catch (error) {
    console.error('创建测试订单失败:', error)
    ElMessage.error('创建测试订单失败: ' + error.message)
  }
}

onMounted(async () => {
  console.log('订单页面加载，当前用户信息:', {
    isLoggedIn: userStore.isLoggedIn,
    username: userStore.username,
    userId: userStore.userId,
    role: userStore.role
  });
  
  // 确保有用户信息
  if (userStore.isLoggedIn) {
    try {
      // 无论是否已有用户ID，都尝试获取最新的用户信息
      const userInfo = await userStore.getInfo();
      console.log('获取到最新用户信息:', userInfo);
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 即使获取用户信息失败，也继续尝试获取订单
    }
  }
  
  // 获取订单列表
  fetchOrders();
})
</script>

<style lang="scss" scoped>
@use '@/styles/variables' as *;

.orders-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .search-form {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 